package com.example.assignment1.server;

import com.example.assignment1.client.TypedStringService;
import com.example.assignment1.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.example.assignment1.server.PersistentThing;
import com.example.assignment1.server.PMF;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class TypedStringServiceImpl extends RemoteServiceServlet implements
		TypedStringService {

	private String test = "foo";
	PersistenceManager pm = PMF.get().getPersistenceManager();
	
	public String addString(String s)
	{
		PersistentThing p = new PersistentThing(s);
		
		try{
			pm.makePersistent(p);
		}
		catch(Exception e)
		{
			return "ERROR IN STORING STRING!!!";
		}
		
		return s;
	}
	
	public String getAllStrings()
	{
		String text = "";
		String query = "select from "+PersistentThing.class.getName() + " order by created_at";
		List<PersistentThing> wordlist = (List<PersistentThing>)pm.newQuery(query).execute();
		if(wordlist.size() == 0)
			return "";
		
		for(int i = 0; i<wordlist.size(); i++)
		{
			PersistentThing temp = wordlist.get(i);
			text = text + (String)(temp.getThing());
			text = text + "<br/>";
		}
		return text;
	}
	
	public String deleteAllStrings()
	{
		Query q = pm.newQuery(PersistentThing.class);
		
		Collection results = (Collection) q.execute();
		Iterator iter = results.iterator();
		while (iter.hasNext()) {
		    pm.deletePersistent(iter.next());
		}

		//String query = "delete from "+PersistentThing.class.getName();
		//pm.newQuery(query).execute();
		//if(wordlist.size() == 0)
		//return "";
		
		//pm.deletePersistentAll(wordlist);
		return "Cleared";
	}
}
